import { config } from '../../config/index';

/** 获取商品列表 */
function mockFetchGoodCategory() {
  const { delay } = require('../_utils/delay');
  const { getCategoryList } = require('../../model/category');
  return delay().then(() => getCategoryList());
}

/** 获取一级分类数据 */
async function fetchFirstLevelCategories() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: 'http://localhost:1002/index/categories/parent',
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          console.log('一级分类返回的原始数据:', res.data);
          
          // 将接口数据转换为组件所需的格式
          const mappedData = res.data.map((item, index) => {
            const categoryData = {
              id: item.categoryId, // 使用categoryId字段
              name: item.categoryName || `分类 ${index + 1}`, // 使用categoryName字段
              thumbnail: '', // 分类暂不使用缩略图
              disabled: false,
              children: [] // 一级分类初始时没有子分类，点击时再加载
            };
            return categoryData;
          });
          
          resolve(mappedData);
        } else {
          // 使用模拟数据作为后备
          const mockData = [
            { id: 1, name: '女装', thumbnail: '', disabled: false, children: [] },
            { id: 2, name: '男装', thumbnail: '', disabled: false, children: [] }
          ];
          resolve(mockData);
        }
      },
      fail: () => {
        // 网络请求失败，返回模拟数据
        const mockData = [
          { id: 1, name: '女装', thumbnail: '', disabled: false, children: [] },
          { id: 2, name: '男装', thumbnail: '', disabled: false, children: [] }
        ];
        resolve(mockData);
      }
    });
  });
}

/** 获取二级分类数据 */
async function fetchSecondLevelCategories(parentId) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `http://localhost:1002/index/categories/children/${parentId}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          const mappedData = res.data.map((item, index) => ({
            id: item.categoryId,
            name: item.categoryName || `子分类 ${index + 1}`,
            thumbnail: 'https://tdesign.gtimg.com/miniprogram/images/goods1.png',
            disabled: false,
            children: []
          }));
          resolve(mappedData);
        } else {
          resolve([]);
        }
      },
      fail: () => {
        resolve([]);
      }
    });
  });
}

/** 获取商品分类列表 */
export function getCategoryList() {
  return fetchFirstLevelCategories();
}

/** 获取二级分类 */
export function getSubCategoryList(parentId) {
  return fetchSecondLevelCategories(parentId);
}
